package com.yilin.medical.utils;


import android.app.Activity;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by liushenghan1 on 15/1/15.
 */
public class InjectUtils {

    public static void inject(Activity activity) {
        inject(activity, activity.getWindow().getDecorView().findViewById(android.R.id.content));
    }


    public static void inject(Fragment fragment) {
        inject(fragment, fragment.getView());
    }

    public static void inject(android.app.Fragment fragment) {
        inject(fragment, fragment.getView());
    }

    public static void inject(Object obj, View view) {
        findView(obj,view);
        click(obj,view);
    }

    private static void findView(Object obj,View view){
        for (Field field : obj.getClass().getDeclaredFields()) {
            Inject inject = field.getAnnotation(Inject.class);
            if (inject != null) {
                Object object = view.findViewById(inject.value());
                field.setAccessible(true);
                try {
                    field.set(obj, object);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void click(final  Object obj,View view) {
//    obj.getClass().getDeclaredMethods();
        for (final Method method : obj.getClass().getDeclaredMethods()) {
            method.setAccessible(true);
            Log.d("InjectUtils", method.toString());
            OnClick click = method.getAnnotation(OnClick.class);
            if (click != null) {

                Log.d("InjectUtils", click.value() + "");
                view.findViewById(click.value()).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            Class<?>[] classes = method.getParameterTypes();
                            if (classes != null && classes[0].isAssignableFrom(View.class)) {
                                method.invoke(obj, v);
                            } else {
                                method.invoke(obj);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

            }
        }
    }


}

